// 网络测试工具
export class NetworkTester {
  private static instance: NetworkTester;
  private testResults: Map<string, any> = new Map();

  static getInstance(): NetworkTester {
    if (!NetworkTester.instance) {
      NetworkTester.instance = new NetworkTester();
    }
    return NetworkTester.instance;
  }

  // 测试单个URL
  async testUrl(url: string): Promise<any> {
    const startTime = Date.now();
    const result = {
      url,
      status: 'pending',
      message: '',
      responseTime: 0,
      error: null,
      timestamp: new Date().toISOString()
    };

    try {
      console.log(`🧪 测试连接: ${url}`);
      
      const response = await fetch(`${url}/test/ping`, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
        },
        // 设置较短的超时时间
        signal: AbortSignal.timeout(10000)
      });

      const responseTime = Date.now() - startTime;
      result.responseTime = responseTime;

      if (response.ok) {
        const data = await response.json();
        result.status = 'success';
        result.message = `连接成功 (${responseTime}ms) - ${data.message}`;
        console.log(`✅ ${url} 连接成功:`, data);
      } else {
        result.status = 'error';
        result.message = `HTTP ${response.status}: ${response.statusText}`;
        console.log(`❌ ${url} HTTP错误:`, response.status, response.statusText);
      }

    } catch (error) {
      const responseTime = Date.now() - startTime;
      result.responseTime = responseTime;
      result.status = 'error';
      result.error = error;
      
      if (error instanceof Error) {
        if (error.name === 'AbortError') {
          result.message = `连接超时 (${responseTime}ms)`;
          console.log(`⏰ ${url} 连接超时`);
        } else if (error.message.includes('Network request failed')) {
          result.message = '网络请求失败 - 可能是地址不可达';
          console.log(`🌐 ${url} 网络请求失败:`, error.message);
        } else if (error.message.includes('fetch')) {
          result.message = 'Fetch API错误 - 可能是CORS或网络问题';
          console.log(`📡 ${url} Fetch错误:`, error.message);
        } else {
          result.message = `连接错误: ${error.message}`;
          console.log(`❌ ${url} 连接错误:`, error.message);
        }
      } else {
        result.message = `未知错误: ${String(error)}`;
        console.log(`❓ ${url} 未知错误:`, error);
      }
    }

    this.testResults.set(url, result);
    return result;
  }

  // 测试所有可能的地址
  async testAllAddresses(): Promise<any[]> {
    const testUrls = [
      'http://localhost:3000',
      'http://10.0.2.2:3000',
      'http://127.0.0.1:3000',
      'http://192.168.1.100:3000',
      'http://192.168.0.100:3000',
    ];

    console.log('🚀 开始全面网络诊断...');
    console.log('测试地址列表:', testUrls);

    const results: any[] = [];
    
    for (const url of testUrls) {
      const result = await this.testUrl(url);
      results.push(result);
      
      // 等待一下再测试下一个
      await new Promise(resolve => setTimeout(resolve, 1000));
    }

    // 分析结果
    this.analyzeResults(results);
    
    return results;
  }

  // 分析测试结果
  private analyzeResults(results: any[]): void {
    console.log('\n📊 网络诊断结果分析:');
    
    const successful = results.filter(r => r.status === 'success');
    const failed = results.filter(r => r.status === 'error');
    
    console.log(`✅ 成功连接: ${successful.length}`);
    console.log(`❌ 失败连接: ${failed.length}`);
    
    if (successful.length > 0) {
      const best = successful.reduce((prev, current) => 
        prev.responseTime < current.responseTime ? prev : current
      );
      console.log(`🏆 最佳连接: ${best.url} (${best.responseTime}ms)`);
      console.log('💡 建议在配置中使用此地址');
    } else {
      console.log('❌ 所有地址都无法连接');
      console.log('🔧 可能的原因:');
      console.log('  1. 后端服务未启动');
      console.log('  2. 后端只监听localhost，未监听0.0.0.0');
      console.log('  3. 防火墙阻止连接');
      console.log('  4. 端口3000被占用');
      console.log('  5. Android模拟器网络配置问题');
    }

    // 显示详细结果
    results.forEach((result, index) => {
      const status = result.status === 'success' ? '✅' : '❌';
      console.log(`${index + 1}. ${status} ${result.url}: ${result.message}`);
    });
  }

  // 获取测试结果
  getResults(): Map<string, any> {
    return this.testResults;
  }

  // 清除测试结果
  clearResults(): void {
    this.testResults.clear();
  }

  // 获取最佳连接地址
  getBestConnection(): string | null {
    const successful = Array.from(this.testResults.values())
      .filter(r => r.status === 'success');
    
    if (successful.length === 0) return null;
    
    const best = successful.reduce((prev, current) => 
      prev.responseTime < current.responseTime ? prev : current
    );
    
    return best.url;
  }
}

export default NetworkTester; 